import legacyPlugin from '@vitejs/plugin-legacy'
import { viteLogo } from './src/core/config'
import Banner from 'vite-plugin-banner'
import * as path from 'path'
import * as dotenv from 'dotenv'
import * as fs from 'fs'
import vuePlugin from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import VueFilePathPlugin from './vitePlugin/componentName/index.js'
import { svgBuilder } from 'vite-auto-import-svg'
import { AddSecret } from './vitePlugin/secret'
// my
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import ViteRestart from 'vite-plugin-restart'
import Components from 'unplugin-vue-components/vite'
// @see https://cn.vitejs.dev/config/
export default ({ mode }) => {
  AddSecret('')
  const NODE_ENV = mode || 'development'
  const envFiles = [`.env.${NODE_ENV}`, '.env']
  for (const file of envFiles) {
    const envConfig = dotenv.parse(fs.readFileSync(file))
    for (const k in envConfig) {
      process.env[k] = envConfig[k]
    }
  }

  viteLogo(process.env)

  const timestamp = Date.parse(new Date())

  const optimizeDeps = {}

  const alias = {
    '@': path.resolve(__dirname, './src'),
    '@common': path.resolve(__dirname, '../common-font'),
    vue$: 'vue/dist/vue.runtime.esm-bundler.js',
  }

  const esbuild = {}

  const rollupOptions = {
    output: {
      entryFileNames: 'assets/[name].[hash].js',
      chunkFileNames: 'assets/[name].[hash].js',
      assetFileNames: 'assets/[name].[hash].[ext]',
    },
  }

  const config = {
    base: process.env.VITE_ROUTER_BASE_PREFIX + '/',
    // base: '/', // 编译后js导入的资源路径
    root: './', // index.html文件所在位置
    publicDir: 'public', // 静态资源文件夹
    resolve: {
      alias,
    },
    define: {
      'process.env': {},
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler', // or "modern"
        },
      },
    },
    server: {
      // 如果使用docker-compose开发模式，设置为false
      open: true,
      port: process.env.VITE_CLI_PORT,
      proxy: {
        // 把key的路径代理到target位置
        // detail: https://cli.vuejs.org/config/#devserver-proxy
        [process.env.VITE_ROUTER_BASE_PREFIX + process.env.VITE_APP_PROXY_PREFIX]: {
          //富文本图片使用
          // 需要代理的路径   例如 '/api'
          target: process.env.VITE_SERVER_PORT
            ? `${process.env.VITE_BASE_PATH}:${process.env.VITE_SERVER_PORT}/`
            : `${process.env.VITE_BASE_PATH}/`, // 代理到 目标路径
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(
              new RegExp(
                '^' + process.env.VITE_ROUTER_BASE_PREFIX + process.env.VITE_APP_PROXY_PREFIX,
              ),
              '',
            ),
        },
        [process.env.VITE_APP_PROXY_PREFIX]: {
          //正常api转发
          target: process.env.VITE_SERVER_PORT
            ? `${process.env.VITE_BASE_PATH}:${process.env.VITE_SERVER_PORT}/`
            : `${process.env.VITE_APP_PROXY_PREFIX}/`, // 代理到 目标路径
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^' + process.env.VITE_APP_PROXY_PREFIX), ''),
        },
      },
    },
    build: {
      minify: 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser
      manifest: false, // 是否产出manifest.json
      sourcemap: false, // 是否产出sourcemap.json
      outDir: 'dist', // 产出目录
      terserOptions: {
        compress: {
          //生产环境时移除console
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions,
    },
    esbuild,
    optimizeDeps,
    plugins: [
      // https://github.com/antfu/unplugin-vue-components
      Components({
        // 组件所在目录，默认是 src/components
        dirs: ['src/components/xuedinge'],
        // 是否深度搜索子目录
        deep: true,
        // 是否将目录名作为组件命名空间
        // directoryAsNamespace: true,
        // allow auto load markdown components under `./src/components/`
        extensions: ['vue', 'md'],
        // allow auto import and register components used in markdown
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
        // dts: 'src/components.d.ts',
      }),
      UnoCSS(),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        dts: 'src/types/auto-import.d.ts',
        vueTemplate: true, // 允许在template模板内使用自动导入的函数
        dirs: ['src/utils/**', 'src/pinia/**'], //'src/plugin/**'
        eslintrc: { enabled: true },
      }),
      ViteRestart({
        // 通过这个插件，在修改vite.config.js文件则不需要重新运行也生效配置
        restart: ['vite.config.js'],
      }),
      process.env.VITE_POSITION === 'open' &&
        vueDevTools({ launchEditor: process.env.VITE_EDITOR }),
      legacyPlugin({
        targets: [
          'Android > 39',
          'Chrome >= 60',
          'Safari >= 10.1',
          'iOS >= 10.3',
          'Firefox >= 54',
          'Edge >= 15',
        ],
      }),
      vuePlugin(),
      svgBuilder('./src/assets/icons/'),
      svgBuilder('./src/plugin/'),
      [Banner(`\n Build based on gin-vue-admin \n Time : ${timestamp}`)],
      VueFilePathPlugin('./src/pathInfo.json'),
    ],
  }
  return config
}
